﻿using System;
using System.Data.Common;
using System.Data.Entity;

using ApplicationBoilerplate.DataProvider;

namespace MVCBootstrap.EntityFramework {

	public class UnitOfWork : UnitOfWorkBase {
		private readonly DbTransaction transaction;
		private Boolean done = false;

		public UnitOfWork(DbTransaction transaction) {
			this.transaction = transaction;
		}

		public override void Commit() {
			if (!done) {
				this.transaction.Commit();
				this.done = true;
			}
		}

		public override void Rollback() {
			if (!done) {
				this.transaction.Rollback();
				this.done = true;
			}
		}

		public override void Dispose(Boolean disposing) {
			if (disposing) {
				if (!done) {
					this.Rollback();
				}
			}
		}
	}

	//public class UnitOfWork : UnitOfWorkBase {
	//    private readonly DbContext context { get; set; }
	//    protected IRepositoryProvider RepositoryProvider { get; set; }

	//    public UnitOfWork(IRepositoryProvider repositoryProvider, DbContext context) {
	//        this.context = context;
	//        InitDbContext();

	//        repositoryProvider.DbContext = this.context;
	//        this.RepositoryProvider = repositoryProvider;
	//    }

	//    public IRepository<Room> Rooms { get { return GetStandardRepo<Room>(); } }
	//    public ISessionsRepository Sessions { get { return GetRepo<ISessionsRepository>(); } }

	//    public void Commit() {
	//        this.context.SaveChanges();
	//    }

	//    protected void InitDbContext() {
	//        // Do NOT enable proxied entities, else serialization fails
	//        DbContext.Configuration.ProxyCreationEnabled = false;
	//        // Load navigation properties explicitly (avoid serialization trouble)
	//        DbContext.Configuration.LazyLoadingEnabled = false;
	//        // Because Web API will perform validation, we don't need/want EF to do so
	//        DbContext.Configuration.ValidateOnSaveEnabled = false;
	//    }

	//    private IRepository<T> GetStandardRepo<T>() where T : class {
	//        return RepositoryProvider.GetRepositoryForEntityType<T>();
	//    }

	//    private T GetRepo<T>() where T : class {
	//        return RepositoryProvider.GetRepository<T>();
	//    }

	//    public void Dispose() {
	//        Dispose(true);
	//        GC.SuppressFinalize(this);
	//    }

	//    protected virtual void Dispose(bool disposing) {
	//        if (disposing) {
	//            if (DbContext != null) {
	//                DbContext.Dispose();
	//            }
	//        }
	//    }
	//}
}